package com.superzlc.vcontroller.message.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.util.Log;

public class BroadcastClient {
	static final String TAG = "BroadcastClient";

	public static void main(String[] args) throws Exception {
		new BroadcastClient().requestIp();
	}

	public String requestIp() {
		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket();
			socket.setSoTimeout(Constants.READ_TIMEOUT_MS);
		} catch (SocketException e) {
			Log.i(TAG, "创建socket失败");
			e.printStackTrace();
			if (socket != null)
				socket.close();
			return null;
		}

		//
		InetAddress inetAddress;
		try {
			inetAddress = InetAddress.getByName(Constants.IP_FOR_BROADCAST);
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
			if (socket != null)
				socket.close();
			return null;
		}
		byte[] bytes4send = Constants.DATA_REQUEST_SERVER_IP.getBytes();
		DatagramPacket packetSend = new DatagramPacket(
				bytes4send, bytes4send.length,
				inetAddress , Constants.PORT_FOR_BROADCAST);

		byte[] bytes4receive = new byte[1024];
		DatagramPacket packet4receive = new DatagramPacket(bytes4receive, bytes4receive.length);
		long start, end;

		// 发送
		Log.i("vjoy", "发送UDP广播请求服务端IP");
		try {
			start = System.currentTimeMillis();
			socket.send(packetSend);
		} catch (IOException e) {
			Log.i(TAG, "发送UDP广播失败");
			e.printStackTrace();
			if (socket != null)
				socket.close();
			return null;
		}

		// 接收
		Log.i("vjoy", "等待接收UDP广播响应");
		try {
			socket.receive(packet4receive);
			end = System.currentTimeMillis();
		} catch (IOException e) {
			Log.i(TAG, "接收UDP广播响应失败");
			e.printStackTrace();
			if (socket != null)
				socket.close();
			return null;
		}

		String str = new String(packet4receive.getData(), 0, packet4receive.getLength());

		String ip = packet4receive.getAddress().getHostAddress();
		Log.i("vjoy", "接收到服务端 " + ip + " 响应数据: " + str + ", 历时ms: " + (end - start));

		String addr = null;
		if (Constants.DATA_REQUEST_ACK_SERVER_IP.equals(str)) { // 这种方式，似乎不能针对多个服务端存在的场景
			addr = ip;
		}
		socket.close();

		return addr;
	}

	public void finalize() throws Throwable {
		super.finalize();
	}
}
